// bluetooth.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp()
const util = require("../../utils/util.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    audio: [
      {
        id: 1,
        src: 'http://www.443w.com/tts/mp3/Lily.mp3',
        title: '确认蓝牙开启',
      }, {
        id: 2,
        src: 'http://www.443w.com/tts/mp3/Liang.mp3',
        title: '蓝牙连接成功并选择套餐',
      }
    ],
    src: '',

    bluetoothDeviceName: "",//GCB19113001191
    deviceId:'',
    remaiderString: '',
    connectionEquipment: '',
    isConnected:10,
    isBloothOpen:10,
    isFirestShow:true,//首次开启蓝牙
    time:60,
    servicesUUID:'',
    characteristicId:'',
    readId:'',
    writeId:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;;
    that.setData({
      bluetoothDeviceName:options.sn,
      region: options.region || '',
      city:options.city || '',
    })
    if (options.resource){
      that.setData({
        resource: options.resource,
        pwd: options.pwd
      })
    }
    // 音频提示
    // var src = that.data.audio[0].src;
    // this.audioCtx = wx.createAudioContext('myAudio')
    // this.audioCtx.setSrc(src)
    // this.audioCtx.play()

    var audioCtx = wx.createInnerAudioContext()
    const version = wx.getSystemInfoSync().SDKVersion;
    if (util.compareVersion(version, '2.3.0') >= 0) {
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false
      })
    }
    audioCtx.src = "http://file.gcb360.com/bluetooth.mp3";
    audioCtx.play();
    audioCtx.onError(function (res) {
      console.log(res)
    })

    wx.stopPullDownRefresh()
    this.initBlue()
  },
  // 初始化蓝牙1.0
  initBlue() {
    var that = this;
    wx.closeBluetoothAdapter({
      success: function(res) {
        wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
          success: function (res) {
            that.getTheBlueDisConnectWithAccident();//监听蓝牙是否会异常断开
            that.findBlue()// 开始获取附近的蓝牙设备
            that.setData({
              isBloothOpen: 20
            })
            that.monitorTheBlue();//监听手机蓝牙的开关
          },
          fail: function (res) {//如果手机上的蓝牙没有打开，可以提醒用户
            if (that.data.isFirestShow) {
              console.log(`1.0isFirestShow:`, that.data.isFirestShow)
              Toast.fail('请开启蓝牙');
            }
            that.setData({
              remaiderString: '等待连接...',
              connectionEquipment: '蓝牙与设备连接失败，请打开蓝牙重新连接,部分手机需要打开GPS',
              isBloothOpen: 10,
              isFirestShow: false,
            })
            console.log(res)
            console.log("1.0蓝牙未打开");
            setTimeout(function () {
              that.initBlue();
            }, 3000)
          }
        })
      },
      fail:err =>{
        console.log('检测本机蓝牙状态',err)
      }
    })
    
  },
  //监听手机蓝牙的开关
  monitorTheBlue: function () {
    var that = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      if (res.available) {
        that.setData({
          isBloothOpen: 20,
          connectionEquipment: '请打开设备，并靠近手机',
        })
        // Toast.success('蓝牙已开启');
      } else {
        that.setData({
          remaiderString: '等待连接...',
          connectionEquipment: '请先打开手机蓝牙，等待连接。（部分手机需要打开GPS）',
          isBloothOpen: 10,
          isFirestShow: false,
        })
        Toast.fail('蓝牙已关闭');
      }
    })
  },
  // 开始获取附近的蓝牙设备2.0
  findBlue() {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
        setTimeout(function(){
          wx.stopBluetoothDevicesDiscovery({
            success: function(res) {
              if (that.data.isFirestShow) {
                Toast.loading('正在搜索设备')
              }
              that.getBlue()//3.0
            },
          })
        },1000)
        
      }
    })
  },
  // 搜索获取附近的所有蓝牙设备 获取附近所有的蓝牙设备的相关信息 获取需要连接蓝牙设备的deviceID 3.0
  getBlue() {
    var that = this
    wx.getBluetoothDevices({
      success: function (res) {
        Toast.clear();
        console.log(`3.0所有设备：`,res.devices);
        var index = 10
        for (var i = 0; i < res.devices.length; i++) {
          if (res.devices[i].name && res.devices[i].localName) {
            var name = res.devices[i].name;
            var localName = res.devices[i].localName;
            if (name == that.data.bluetoothDeviceName || localName == that.data.bluetoothDeviceName) {
              index = 20
              that.setData({
                deviceId: res.devices[i].deviceId,
                connectionEquipment: '已连接到设备：' + res.devices[i].localName,
                remaiderString: '等待连接...',
              })
              console.log("3.0连接的设备：" + that.data.deviceId + ',' + localName);
              that.connetBlue();//4.0
              // return;
            }
          }
        }
        if (index == 10) {
          if (that.data.isFirestShow) {
            Toast.loading('未搜索到配套设备')
          }
          that.setData({
            connectionEquipment: '请打开设备，并靠近手机',
            remaiderString: '等待连接...',
            isFirestShow: false,
          })
        }
      },
      fail: function () {
        if (that.data.isFirestShow) {
          Toast.loading('未搜索到配套设备')
        }
        that.setData({
          connectionEquipment: '请打开设备，并靠近手机',
          remaiderString: '等待连接...',
          isFirestShow: false,
        })
      },
      complete: function () {
        // that.setData({
        //   isFirestShow: false,
        // })
      },
    })
  },
  // 连接蓝牙设备 4.0
  connetBlue() {
    var that = this;
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: that.data.deviceId,//设备id
      success: function (res) {
        that.setData({
          remaiderString: '等待连接...',
        })
        var isConnect = that.data.isConnected;
        if (isConnect == 10) {
          that.getServiceId()//5.0
          that.setData({
            isConnected: 20,
          })
        }
      },
      fail: function (res) {
        that.setData({
          isFirestShow:false,
          connectionEquipment: '请打开设备，并靠近手机',
          remaiderString: '连接失败',
        })
        console.log(`4.0连接失败：`,res)
      },
    })
  },
  // 连接上需要的蓝牙设备之后，获取这个蓝牙设备的服务uuid 5.0
  getServiceId() {
    var that = this
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      success: function (res) {
        console.log('5.0服务列表', res.services)
        var servicesUUID ='';
        for(let i = 0;i<res.services.length;i++){
          var uuidHead = res.services[i].uuid.substring(0,8)
          if (uuidHead == '0000FFF0'){
            servicesUUID = res.services[i].uuid;
            break;
          }
        }
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
          serviceId: servicesUUID,// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
          success: function (ress) {
            console.log("5.0", ress.characteristics)
            if (ress.characteristics[0].properties.write == true) {
              that.setData({
                servicesUUID: servicesUUID,
                writeId: ress.characteristics[0].uuid,//用来写入的值
                readId: ress.characteristics[0].uuid
              })
              if (that.data.resource || that.data.resource =='charging'){
                that.writeData(that.data.pwd)
              }else{
                that.scanCodeAPI();
              }
              return;
            }
          }
        })
      }
    })
  },
  // 扫码后连接成功后获取套餐列表API
  scanCodeAPI: function () {
    var that = this;
    var data = { sn: that.data.bluetoothDeviceName, region: that.data.region, city: that.data.city };
    app.post('order/menu', data).then((res) => {
      if (res.code == 200) {
        console.log(res)
        if (res.data.advertising !== null) {
          app.globalData.swiper = res.data.advertising;
          wx.setStorageSync('swiper', res.data.advertising);
        }
        var advertising = res.data.advertising || app.globalData.swiper || '';
        var bluetoothIDs = {
          deviceId: that.data.deviceId,
          servicesUUID: that.data.servicesUUID,
          readId: that.data.readId,
          writeId: that.data.writeId
        }
        wx.navigateTo({
          url: '../scanPay/scanPay?orderlist=' + JSON.stringify(res.data.product) + '&sn=' + that.data.bluetoothDeviceName + '&advertise=' + JSON.stringify(advertising) + '&bluetoothIDs=' + JSON.stringify(bluetoothIDs) + '&shopname=' + res.data.shop.shopname,
          //deviceId,servicesUUID,readId,writeId
        })
      } else if (res.code == 404) {//未激活设备
        console.log(res.message)
        Toast.loading(res.message);
        that.setData({
          remaiderString: "请联系商家激活设备",
        })
      } else if (res.code == 500) {
        console.log(res)
        var entity = res.entity;
        wx.showModal({
          title: '提示',
          content: '您还有一笔订单没有结束，请问是否结束订单？（结束订单无法激活设备，但如需重新激活设备需要重新支付生成订单）',
          confirmText: '结束订单',
          success: res => {
            if (res.confirm) {
              var data = { id: entity[0].id };
              app.post('order/closeOrder', data).then((res) => {
                if (res.code == 200) {
                  Toast('已结束订单，如需充电，请重新扫码支付充电');
                  wx.navigateBack({
                    delta: 1
                  })
                } else {
                  console.log(res)
                }
              }).catch((errMsg) => {
                console.log(errMsg);
              })
            }
          }
        })
      } else if (res.code == 409) {//设备在使用
        if (app.globalData.order) {
          if (sn == app.globalData.order[0].devicesn) {
            var data = {
              order: app.globalData.order,
              advertising: app.globalData.swiper
            }
            console.log(`409`, data)
          }
        } else {
          Toast.loading(res.message);
        }
      } else {
        wx.showToast({
          title: '获取失败',
        })
      }
    }).catch((errMsg) => {
      console.log(errMsg);//错误提示信息
    })
  },


  // 向低功耗蓝牙设备特征值中写入二进制数据 6.0
  writeData(pwd) {
    var that = this;
    let buffer = util.hexStringToArrayBuffer(pwd);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.writeId, 
      value: buffer,
      success: function (res) {
        // 设备返回的方法
        console.log('7.0writeBLECharacteristicValue success:', res.errMsg)
        // var pages = getCurrentPages();
        // var beforePage = pages[pages.length - 2];
        // beforePage.onload();
        wx.navigateBack({
          delta: 1,
        })
        that.readData()
      }, fail: function (res) {
        console.log('7.0writeBLECharacteristicValue--fail:', res,res.errMsg)
      }
    })
  },
  // 读取低功耗蓝牙设备的特征值的二进制数据值 7.0
  readData(uuid) {
    var that = this;
    wx.readBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.servicesUUID,
      characteristicId: that.data.readId,  
      success: function (res) {
        // 设备返回的方法
        console.log('readBLECharacteristicValue:', res.errCode)
        wx.onBLECharacteristicValueChange(function (res) {
          var nonceId = util.ab2hex(res.value)
          console.info("蓝牙测试返回的数据", res.value, nonceId);
          var nonceId = util.ab2hex(res.value)
        })
      }, fail: function (res) {
        console.log('readBLECharacteristicValue--fail:', res.errCode)
      }
    })
  },

  // 监听异常断开
  getTheBlueDisConnectWithAccident: function (e) {
    var that = this;
    wx.onBLEConnectionStateChange(function (res) {
      console.log(`监听异常断开:`,res)
      if (!res.connected) {
        wx.closeBluetoothAdapter({
          success: function (res) {
            wx.openBluetoothAdapter({
              success: function (res) {
              },
            })
          },
        })
        that.setData({
          remaiderString: "等待连接...",
          ishindden: true,
          isSugarHidden: true,
          isConnected: 10,
          isFirestShow: false,
          testResultIndex: 0,
        })
        that.countdown()//开启计时
      }
    })
  },
  // 异常断开再次开始
  countdown: function () {
    var that = this;
    that.initBlue(that);          //这步很重要，没有这步，重复点击会出现多个定时器
    var time = that.data.time;
    console.log("倒计时开始")
    var interval = setInterval(function () {
      time--;
      that.setData({
        time: time
      })
      if (time == 0) {          //归0时回到60
        var countId = that.data.isConnected;
        if (countId == 10) {
          that.findBlue()
        }
      }
    }, 1000)
    that.setData({
      interval: interval
    })
  },


})